<template>
  <panel-head></panel-head>
  <el-card style="min-height: 100%">
    <el-button
      type="primary"
      size="small"
      icon="Plus"
      @click="dialogFormVisible = true"
      >新增</el-button
    >
    <el-popconfirm title="是否确认删除？" confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF" @confirm="handleConfirmDelete">
      <template #reference>
        <el-button type="danger" icon="Delete" size="small">Delete</el-button>
      </template>
    </el-popconfirm>
    <!-- 表格 -->
    <el-table
      :data="permissionTableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column prop="id" label="id" />

      <el-table-column prop="name" label="昵称" show-overflow-tooltip />

      <el-table-column prop="avatar" label="头像" show-overflow-tooltip>
        <template #default="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.avatar" />
        </template>
      </el-table-column>

      <el-table-column prop="mobile" label="手机号" />

      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          {{ scope.row.sex === "1" ? "男" : "女" }}
        </template>
      </el-table-column>

      <el-table-column prop="permissions_id" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.active ? 'success' : 'danger'">
            {{ scope.row.active ? "正常" : "失效" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="create_time" label="时间">
        <template #default="scope">
          <div class="flex">
            <el-icon><Clock /></el-icon>
            <span>{{ scope.row.create_time }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="open(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-box">
      <el-pagination
        v-model:current-page="paginationData.pageNum"
        :page-size="paginationData.pageSize"
        layout="total, prev, pager, next"
        :total="permissionTableTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <!-- 弹框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :before-close="handleBeforeClose"
    title="陪护师"
    width="500px"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item prop="id" v-show="false">
        <el-input v-model="form.id" />
      </el-form-item>

      <el-form-item prop="name" label="昵称">
        <el-input v-model="form.name" placeholder="请填写" />
      </el-form-item>

      <el-form-item prop="avatar" label="头像">
        <el-button v-if="!form.avatar" @click="dialogImgVisible = true"
          >点击上传</el-button
        >
        <el-image
          v-else
          @click="dialogImgVisible = true"
          :src="form.avatar"
          style="width: 100px; height: 100px"
        />
      </el-form-item>

      <el-form-item prop="sex" label="性别">
        <el-select v-model="form.sex" placeholder="请选择">
          <el-option label="男" value="1" />
          <el-option label="女" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item prop="age" label="年龄">
        <el-input-number
          v-model="form.age"
          :min="1"
          :max="100"
          placeholder="请填写"
        />
      </el-form-item>

      <el-form-item prop="mobile" label="手机号">
        <el-input v-model="form.mobile" placeholder="请填写" />
      </el-form-item>

      <el-form-item prop="active" label="是否生效">
        <el-radio-group v-model="form.active">
          <el-radio :value="0">失效</el-radio>
          <el-radio :value="1">生效</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm(formRef)"
          >确认</el-button
        >
      </div>
    </template>
  </el-dialog>

  <!-- 选择弹框图片 -->
  <el-dialog v-model="dialogImgVisible" title="选择图片" width="680px">
    <div class="image-list">
      <div
        v-for="(item, index) in fileList"
        :key="item.name"
        class="img-box"
        @click="selectIndex = index"
      >
        <div v-if="selectIndex === index" class="select">
          <el-icon color="#0f0">
            <Check />
          </el-icon>
        </div>
        <el-image style="width: 148px; height: 148px" :src="item.url" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogImgVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChoose">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import dayjs from "dayjs";
import { useStore } from "vuex";
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  authAdminApi,
  getMenuSelectListApi,
  getPhotoListApi,
  createCompanionApi,
  getCompanionListApi,
  companionDeleteApi
} from "../../../api/index";
import { ElMessage } from "element-plus";

const store = useStore();

/* 表单数据 */
const form = reactive({
  id: "",
  mobile: "",
  active: 1,
  avatar: "",
  name: "",
  sex: "1",
});

const rules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入" }],
});

/** 获取下拉权限列表 */
const permissionData = ref([]);
const getMenuList = async () => {
  const { code, data } = await getMenuSelectListApi();
  if (code === 10000) {
    permissionData.value = data;
  }
};

/** 表单提交 */
const formRef = ref();
const treeRef = ref();
const handleConfirm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      console.log(111, form);
      // 获取选择的数据
      const { code, data } = await createCompanionApi({
        ...form,
      });
      if (code === 10000) {
        ElMessage.success(data);
        handleBeforeClose();
        getListData();
      }
    } else {
      console.log("error submit!");
    }
  });
};

/** 列表数据 */
const paginationData = reactive({
  pageNum: 1,
  pageSize: 10,
});

/** 表格数据 */
const permissionTableData = ref([]);
const permissionTableTotal = ref([]);
const getListData = async () => {
  const { code, data } = await getCompanionListApi({
    ...paginationData,
  });
  if (code === 10000) {
    data.list.forEach((item) => {
      item.create_time = dayjs(item.create_time).format("YYYY-MM-DD");
    });
    permissionTableData.value = data.list;
    permissionTableTotal.value = data.total;
  }
};

/** 复选框 */
const selectTableData = ref([])
const handleSelectionChange = (e) => {
  selectTableData.value = e.map(item => ({ id: item.id}));
};

/** 删除 */
const handleConfirmDelete = async () => {
  if (!selectTableData.value.length) {
    return ElMessage.error('请选择至少一条数据')
  }
  const { code, data } = await companionDeleteApi({
    id: selectTableData.value
  })
  if (code === 10000) {
    ElMessage.success(data)
    getListData()
  }
}

/**  页数改变 */
const handleSizeChange = (val) => {
  paginationData.pageSize = val;
  getListData();
};

/** 上一页、下一页 */
const handleCurrentChange = (val) => {
  paginationData.pageNum = val;
  getListData();
};

/** 打开弹框 */
const dialogFormVisible = ref(false);
const open = (rowData = {}) => {
  dialogFormVisible.value = true;
  nextTick(() => {
    if (Object.keys(rowData).length) {
      Object.assign(form, {
        ...rowData,
      });
    }
  });
};

/** 关闭弹框 */
const handleBeforeClose = () => {
  form.id = "";
  dialogFormVisible.value = false;
  formRef.value.resetFields();
};

/**
 * 图片弹框相关
 */
const dialogImgVisible = ref(false);
const fileList = ref([]);
const getPhotoList = async () => {
  const { code, data } = await getPhotoListApi();
  if (code === 10000) {
    fileList.value = data;
  }
};

const selectIndex = ref(0);
const handleChoose = () => {
  form.avatar = fileList.value[selectIndex.value].url;
  dialogImgVisible.value = false;
};

onMounted(() => {
  getMenuList();
  getListData();
  getPhotoList();
});
</script>

<style lang="less" scoped>
.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  overflow-y: auto;

  .img-box {
    position: relative;
    margin: 7px;
    cursor: pointer;

    .select {
      position: absolute;
      left: 0;
      top: 0;
      width: 34px;
      height: 34px;
      z-index: 99;
    }
  }
}
</style>